#========================================
# author: changlong.zang
#   mail: zclongpop@163.com
#   date: Thu, 05 May 2016, 12:28:14
#========================================
import os, re, glob
import maya.cmds as mc
from foleyUtils import uiTool, mayaTool
import shaderUI, shaderCore
#--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
class UI(shaderUI.QtGui.QMainWindow, shaderUI.Ui_VHQ_SHADING_IO_WND):
    '''
    '''

    def __init__(self, parent=uiTool.getMayaWindow()):
        '''
        '''
        if uiTool.windowExists('VHQ_SHADING_IO_WND'):
            return

        super(UI, self).__init__(parent)
        self.setupUi(self)
        self.show()



    #===============================================
    # Utils
    #===============================================
    def __auto_complation_path(self):
        '''
        '''
        path = mc.file(q=True, sn=True)
        while True:
            if path == os.path.dirname(path):
                break

            if os.path.isdir(os.path.join(path, 'shader')):
                path = os.path.join(path, 'shader')
                break

            path = os.path.dirname(path)

        return path





    def __get_refrence_shader_files(self):
        '''
        '''
        for ref in mayaTool.find_all_ref_path(mc.file(q=True, sn=True)):
            path = ref
            while True:
                if os.path.dirname(path) == path:
                    break

                if os.path.isdir(os.path.join(path, 'shader')):
                    path = os.path.join(path, 'shader')
                    break

                if not os.path.isdir(os.path.dirname(path)):
                    break

                path = os.path.dirname(path)

            for f in os.listdir(path):
                if not re.search('\.m[ab]$', f):
                    continue

                yield os.path.normpath(os.path.join(path, f))





    def __get_project_shader_files(self):
        '''
        '''
        project_root_path    = str(self.let_project_root_path.text())
        shader_files_pattern = os.path.normpath(os.path.join(project_root_path, 'VFX', 'assets', 'models', '*', '*', 'shader', '*.m[ab]'))
        for path in glob.iglob(shader_files_pattern):
            yield path



    #===============================================
    # Export
    #===============================================
    def on_let_export_shader_path_textChanged(self, text):
        '''
        '''
        shaderPath = str(text)
        if not shaderPath:
            return
        dataPath   = '{0}.xml'.format(os.path.splitext(shaderPath)[0])
        self.let_export_data_path.setText(dataPath)




    def on_btn_set_export_shader_path_clicked(self, args=None):
        '''
        '''
        if args==None:
            return
        path = mc.fileDialog2(fm=0, dir=self.__auto_complation_path(), ff='Maya ASCII (*.ma);;Maya Binary (*.mb);;All Files (*.*)')
        if path:
            self.let_export_shader_path.setText(path[0])





    def on_btn_set_export_data_path_clicked(self, args=None):
        '''
        '''
        if args==None:
            return
        path = mc.fileDialog2(fm=0, dir=self.__auto_complation_path(), ff='XML Files (*.xml)')
        if path:
            self.let_export_data_path.setText(path[0])





    def on_btn_export_shader_by_sel_clicked(self, args=None):
        '''
        '''
        if args==None:
            return

        if not uiTool.warning('Start Export selection gemetry\'s shader and connection data to file ? ?', 'a'):
            return

        mc.select(hi=True)

        shader_path = str(self.let_export_shader_path.text())
        data_path   = str(self.let_export_data_path.text())

        shaderCore.export_sel_SG_connect_data(data_path)
        shaderCore.export_sel_SG_nodes(shader_path)

        uiTool.warning('Export selection shader and data finished !!', 's')





    def on_btn_export_shader_by_all_clicked(self, args=None):
        '''
        '''
        if args==None:
            return

        if not uiTool.warning('Start Export all shaders and connection data to file ? ?', 'a'):
            return

        shader_path = str(self.let_export_shader_path.text())
        data_path   = str(self.let_export_data_path.text())

        shaderCore.export_all_SG_connect_data(data_path)
        shaderCore.export_all_SG_nodes(shader_path)

        uiTool.warning('Export all shader and data finished !!', 's')


    #===============================================
    # Import
    #===============================================
    def on_let_import_shader_path_textChanged(self, text):
        '''
        '''
        shaderPath = str(text)
        if not shaderPath:
            return

        dataPath   = '{0}.xml'.format(os.path.splitext(shaderPath)[0])
        if not os.path.isfile(dataPath):
            return

        self.let_import_data_path.setText(dataPath)





    def on_btn_set_import_shader_path_clicked(self, args=None):
        '''
        '''
        if args==None:
            return
        path = mc.fileDialog2(fm=1, dir=self.__auto_complation_path(), ff='Maya ASCII (*.ma);;Maya Binary (*.mb);;All Files (*.*)')
        if path:
            self.let_import_shader_path.setText(path[0])





    def on_btn_set_import_data_path_clicked(self, args=None):
        '''
        '''
        if args==None:
            return
        path = mc.fileDialog2(fm=1, dir=self.__auto_complation_path(), ff='XML Files (*.xml)')
        if path:
            self.let_import_data_path.setText(path[0])





    def on_btn_import_shader_by_sel_clicked(self, args=None):
        '''
        '''
        if args==None:
            return

        if not uiTool.warning('Import shader and connection data to selection geometry ? ?', 'a'):
            return

        mc.select(hi=True)

        shader_path = str(self.let_import_shader_path.text())
        data_path   = str(self.let_import_data_path.text())

        shaderCore.import_SG_nodes(shader_path)
        shaderCore.import_data_to_sel(data_path, self.rnd_match_geo_by_name.isChecked())

        uiTool.warning('Import shader and data to selection finished !!', 's')





    def on_btn_import_shader_by_all_clicked(self, args=None):
        '''
        '''
        if args==None:
            return

        if not uiTool.warning('Import shader and connection data to all geometry ? ?', 'a'):
            return

        shader_path = str(self.let_import_shader_path.text())
        data_path   = str(self.let_import_data_path.text())

        shaderCore.import_SG_nodes(shader_path)
        shaderCore.import_data_to_all(data_path, self.rnd_match_geo_by_name.isChecked())

        uiTool.warning('Import shader and data to all finished !!', 's')


    #===============================================
    # Merge
    #===============================================
    def on_btn_select_project_path_clicked(self, args=None):
        '''
        '''
        if args==None:
            return
        path = mc.fileDialog2(fm=3, okc='Select')
        if path:
            self.let_project_root_path.setText(path[0])




    def __get_merge_shader_path_list(self):
        '''
        '''
        if self.rdn_search_reference_shaders.isChecked():
            self.__shader_path_list = self.__get_refrence_shader_files()
        else:
            self.__shader_path_list = self.__get_project_shader_files()




    def on_btn_merge_shader_by_all_clicked(self, args=None):
        '''
        '''
        if args==None:
            return

        if not uiTool.warning('Start merge shader to all objects ? ?', 'a'):
            return

        self.__get_merge_shader_path_list()
        shaderCore.merge_data_to_scene(self.__shader_path_list, 0, self.rnd_match_geo_by_name.isChecked())

        uiTool.warning('Merge shader and conenction data finished !!', 's')




    def on_btn_merge_shader_by_sel_clicked(self, args=None):
        '''
        '''
        if args==None:
            return

        if not uiTool.warning('Start merge shader to selection objects ? ?', 'a'):
            return

        self.__get_merge_shader_path_list()
        shaderCore.merge_data_to_scene(self.__shader_path_list, 1, self.rnd_match_geo_by_name.isChecked())

        uiTool.warning('Merge shader and conenction data finished !!', 's')




    def on_btn_merge_shader_by_view_clicked(self, args=None):
        '''
        '''
        if args==None:
            return

        if not uiTool.warning('Start merge shader to camera view objects ? ?', 'a'):
            return

        self.__get_merge_shader_path_list()
        shaderCore.merge_data_to_scene(self.__shader_path_list, 2, self.rnd_match_geo_by_name.isChecked())

        uiTool.warning('Merge shader and conenction data finished !!', 's')
